package blink.view.main_panel;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ResourceBundle;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import blink.guimodel.TaskListModel;
import blink.model.Experiment;
import blink.model.Task;
import blink.model.TaskBD;
import blink.view.experiment.ExperimentPanel;
import blink.view.task.TaskPanel;
import blink.view.task.TaskPanelListener;

public class MainFrame {

	private JFrame frame;
	public static final TaskBD taskBD=new TaskBD(new File(Messages.getString("MainFrame.0"))); //$NON-NLS-1$
	private TaskListModel tasksListModel = new TaskListModel(taskBD);
	ResourceBundle bundle = ResourceBundle.getBundle(Messages.getString("MainFrame.1")); //$NON-NLS-1$

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {

		try {
			for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
				if (Messages.getString("MainFrame.2").equals(info.getName())) { //$NON-NLS-1$
					UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (Exception e) {
			// If Nimbus is not available, you can set the GUI to another look
			// and feel.
		}

		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainFrame window = new MainFrame();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public MainFrame() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	@SuppressWarnings("unchecked")
	private void initialize() {

		frame = new JFrame();
		frame.setMinimumSize(new Dimension(800, 500));
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setExtendedState(Frame.MAXIMIZED_BOTH);

		ButtonListener buttonListener = new ButtonListener();

		menuBar = new JMenuBar();
		frame.setJMenuBar(menuBar);

		mnNewMenu = new JMenu(Messages.getString("MainFrame.3")); //$NON-NLS-1$
		menuBar.add(mnNewMenu);

		mntmNewMenuItem = new JMenuItem(Messages.getString("MainFrame.4")); //$NON-NLS-1$
		mnNewMenu.add(mntmNewMenuItem);
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWeights = new double[] { 1.0, 1.0, 6.0 };
		gridBagLayout.rowWeights = new double[] { 0.0, 1.0, 0.0, 0.0 };
		frame.getContentPane().setLayout(gridBagLayout);

		toolBar = new JToolBar();
		toolBar.setFloatable(false);
		GridBagConstraints gbc_toolBar = new GridBagConstraints();
		gbc_toolBar.gridwidth = 4;
		gbc_toolBar.insets = new Insets(0, 0, 5, 0);
		gbc_toolBar.anchor = GridBagConstraints.FIRST_LINE_END;
		gbc_toolBar.fill = GridBagConstraints.HORIZONTAL;
		gbc_toolBar.gridx = 0;
		gbc_toolBar.gridy = 0;
		frame.getContentPane().add(toolBar, gbc_toolBar);

		buttonExperiment = new JToggleButton(Messages.getString("MainFrame.5")); //$NON-NLS-1$
		buttonExperiment.setName(Messages.getString("MainFrame.6")); //$NON-NLS-1$
		toolBar.add(buttonExperiment);

		buttonTasks = new JToggleButton(Messages.getString("MainFrame.7")); //$NON-NLS-1$
		buttonTasks.setName(Messages.getString("MainFrame.8")); //$NON-NLS-1$
		toolBar.add(buttonTasks);

		buttonGroup = new ButtonGroup();
		buttonGroup.add(buttonExperiment);
		buttonGroup.add(buttonTasks);
		
		jListTask = new JList(tasksListModel);
		jListTask.setBorder(new LineBorder(Color.LIGHT_GRAY, 1, true));
		jListTask.setVisibleRowCount(15);
		jListTask.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		jListTask.addListSelectionListener(alsl);
		GridBagConstraints gbc_list = new GridBagConstraints();
		gbc_list.fill = GridBagConstraints.BOTH;
		gbc_list.insets = new Insets(5, 5, 5, 5);
		gbc_list.gridwidth = 2;
		gbc_list.gridx = 0;
		gbc_list.gridy = 1;
		frame.getContentPane().add(jListTask, gbc_list);

		GridBagConstraints gbc_panel = new GridBagConstraints();
		gbc_panel.fill = GridBagConstraints.BOTH;
		gbc_panel.insets = new Insets(0, 0, 5, 5);
		gbc_panel.gridx = 2;
		gbc_panel.gridy = 1;
		frame.getContentPane().add(mainPanel, gbc_panel);
		mainPanel.setLayout(new CardLayout(0, 0));

		Experiment exp = new Experiment();
		experimentPanel = new ExperimentPanel(exp,this);

		Task t = new Task();
		taskPanel = new TaskPanel(t);
		taskPanel.addTaskPanelListener(tpl);
		taskPanel.setBackground(new Color(214, 217, 223));

		mainPanel.add(experimentPanel, Messages.getString("MainFrame.9")); //$NON-NLS-1$
		mainPanel.add(taskPanel, Messages.getString("MainFrame.10")); //$NON-NLS-1$
		
		btRemTask = new JButton(Messages.getString("MainFrame.11")); //$NON-NLS-1$
		GridBagConstraints gbc_btnNewButton_1 = new GridBagConstraints();
		gbc_btnNewButton_1.insets = new Insets(0, 0, 5, 0);
		gbc_btnNewButton_1.fill = GridBagConstraints.BOTH;
		gbc_btnNewButton_1.gridx = 1;
		gbc_btnNewButton_1.gridy = 3;
		btRemTask.addActionListener(buttonListener);
		frame.getContentPane().add(btRemTask, gbc_btnNewButton_1);

		btAddTask = new JButton(Messages.getString("MainFrame.12")); //$NON-NLS-1$
		GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
		gbc_btnNewButton.insets = new Insets(0, 5, 5, 5);
		gbc_btnNewButton.fill = GridBagConstraints.BOTH;
		gbc_btnNewButton.gridx = 0;
		gbc_btnNewButton.gridy = 3;
		btAddTask.addActionListener(buttonListener);
		frame.getContentPane().add(btAddTask, gbc_btnNewButton);

		buttonExperiment.addActionListener(buttonListener);
		buttonTasks.addActionListener(buttonListener);
	}
	
	private void enableAllContainedComp(Container container) {
        for (Component c : container.getComponents()) {
            if (c instanceof Container && ((Container) c).getComponentCount() > 0 && c.getName()!=bundle.getString(Messages.getString("MainFrame.13"))) { //$NON-NLS-1$
                enableAllContainedComp(((Container) c));
            }
            c.setEnabled(jListTask.getSelectedIndex() != -1);
        }
    }
	
	TaskPanelListener tpl=new TaskPanelListener() {	
		@Override
		public void saveActionPerformed(ActionEvent ae) {
			tasksListModel.replaceTask(jListTask.getSelectedIndex(),(Task)((TaskPanel)ae.getSource()).getModel());
		}
		
		@Override
		public void deleteActionPerformed(ActionEvent ae) {
			btRemTaskActionPerformed(ae);
		}
	};
	
	ListSelectionListener alsl = new ListSelectionListener() {
		public void valueChanged(ListSelectionEvent lse) {
			enableAllContainedComp(taskPanel);
			if (lse.getSource() == jListTask && jListTask.getSelectedIndex()!=-1)
				((TaskPanel) taskPanel).setModel((Task)jListTask.getSelectedValue());
		}
	};

	// Code for dispatching events from components to event handlers.
	private class ButtonListener implements ActionListener{
		ButtonListener() {}

		public void actionPerformed(ActionEvent evt) {
			if (evt.getSource() == buttonExperiment) {
				MainFrame.this.btDisplayExperienceActionPerformed(evt);
			} else if (evt.getSource() == buttonTasks) {
				MainFrame.this.btDisplayTaskActionPerformed(evt);
			} else 
				if (evt.getSource() == btAddTask) {
				MainFrame.this.btAddTaskActionPerformed(evt);
				jListTask.setSelectedIndex(jListTask.getLastVisibleIndex());
			} else if (evt.getSource() == btRemTask) {
				MainFrame.this.btRemTaskActionPerformed(evt);
			} 
		}
	}

	private void btDisplayExperienceActionPerformed(ActionEvent evt) {
		CardLayout clMainPanel = (CardLayout) (mainPanel.getLayout());
		clMainPanel.show(mainPanel, Messages.getString("MainFrame.14")); //$NON-NLS-1$
	}

	private void btDisplayTaskActionPerformed(ActionEvent evt) {
		CardLayout clMainPanel = (CardLayout) (mainPanel.getLayout());
		clMainPanel.show(mainPanel, Messages.getString("MainFrame.15")); //$NON-NLS-1$
	}

	private void btAddTaskActionPerformed(ActionEvent evt) {
		tasksListModel.createNewTask();
	}

	private void btRemTaskActionPerformed(ActionEvent evt) {
		tasksListModel.removeTask(jListTask.getSelectedIndex());
		enableAllContainedComp(taskPanel);
	}
	
	public JList getTaskList(){
		return jListTask;
	}

	private JMenuBar menuBar;
	private JMenu mnNewMenu;
	private JMenuItem mntmNewMenuItem;
	private JToolBar toolBar;
	private JToggleButton buttonExperiment;
	private JToggleButton buttonTasks;
	private ButtonGroup buttonGroup;
	private JList jListTask;
	private Panel mainPanel = new Panel();
	private JButton btRemTask;
	private JButton btAddTask;
	private ExperimentPanel experimentPanel;
	private TaskPanel taskPanel;

}
